from django.core.management.base import BaseCommand
from django.utils import timezone
from data_service.models import DataSource, DataSyncTask
from data_service.sync_service import sync_service


class Command(BaseCommand):
    help = '同步基金数据'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--sync-type',
            type=str,
            default='fund_data',
            help='同步类型: fund_data, fund_net_value, market_data'
        )
        parser.add_argument(
            '--fund-code',
            type=str,
            help='基金代码（用于净值同步）'
        )
        parser.add_argument(
            '--days',
            type=int,
            default=30,
            help='同步天数（用于净值同步）'
        )
    
    def handle(self, *args, **options):
        sync_type = options['sync_type']
        fund_code = options.get('fund_code')
        days = options['days']
        
        self.stdout.write(f'开始同步数据，类型: {sync_type}')
        
        try:
            # 获取或创建数据源
            data_source, created = DataSource.objects.get_or_create(
                name='AKShare数据源',
                defaults={
                    'source_type': 'akshare',
                    'config': {}
                }
            )
            
            if created:
                self.stdout.write('创建了新的数据源')
            
            # 创建同步任务
            sync_params = {}
            if sync_type == 'fund_net_value' and fund_code:
                sync_params = {
                    'fund_code': fund_code,
                    'days': days
                }
            
            task = DataSyncTask.objects.create(
                name=f'手动同步-{sync_type}-{timezone.now().strftime("%Y%m%d_%H%M%S")}',
                data_source=data_source,
                sync_type=sync_type,
                sync_params=sync_params,
                status='pending'
            )
            
            self.stdout.write(f'创建同步任务: {task.name}')
            
            # 执行同步
            result = sync_service.execute_sync_task(task.id)
            
            if result['status'] == 'success':
                self.stdout.write(
                    self.style.SUCCESS(f'同步成功: {result["message"]}')
                )
            else:
                self.stdout.write(
                    self.style.ERROR(f'同步失败: {result["message"]}')
                )
                
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'同步过程中发生错误: {str(e)}')
            )